/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.ventas;

import Model.Producto;
import Presenter.EnvioPedidoPresenter;
import Presenter.ProductoPresenter;        
import View.components.Index;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import Principals.Validadores;

/**
 *
 * @author Paola
 */
public class Frm_BuscarProducto extends javax.swing.JDesktopPane {
    Validadores val = new Validadores();
    private DefaultTableModel mdlBuscarProducto ;
 
    /**
     * Creates new form Frm_BuscarProducto
     */
    public Frm_BuscarProducto() {
        initComponents();
        val.desactivarAccionPegar(txtNombre);
        EnvioPedidoPresenter.actualizarEnvioPedido() ; 
        tblBuscarProducto.getTableHeader().setReorderingAllowed(false);
        mdlBuscarProducto = new DefaultTableModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlBuscarProducto = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JToggleButton();
        pnlResultadosProducto = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblBuscarProducto = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        btnToolNuevo = new javax.swing.JButton();
        btnToolModificar = new javax.swing.JButton();
        btnToolGuardar = new javax.swing.JButton();
        btnToolEliminar = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        btnToolLimpiar = new javax.swing.JButton();
        btnToolBuscar = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnToolCancelar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();

        setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        pnlBuscarProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Búsqueda"));

        lblNombre.setText("Nombre:");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        btnBuscar.setText("Buscar");
        btnBuscar.setAutoscrolls(true);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBuscarProductoLayout = new javax.swing.GroupLayout(pnlBuscarProducto);
        pnlBuscarProducto.setLayout(pnlBuscarProductoLayout);
        pnlBuscarProductoLayout.setHorizontalGroup(
            pnlBuscarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBuscarProductoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblNombre)
                .addGap(18, 18, 18)
                .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnBuscar)
                .addContainerGap())
        );
        pnlBuscarProductoLayout.setVerticalGroup(
            pnlBuscarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBuscarProductoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlBuscarProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pnlResultadosProducto.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));

        tblBuscarProducto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id Producto", "Nombre", "Precio Costo (S/.)", "Precio Lista (S/.)", "Stock", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblBuscarProducto);

        javax.swing.GroupLayout pnlResultadosProductoLayout = new javax.swing.GroupLayout(pnlResultadosProducto);
        pnlResultadosProducto.setLayout(pnlResultadosProductoLayout);
        pnlResultadosProductoLayout.setHorizontalGroup(
            pnlResultadosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE)
        );
        pnlResultadosProductoLayout.setVerticalGroup(
            pnlResultadosProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
        );

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setBorderPainted(false);

        btnToolNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Nuevo.png"))); // NOI18N
        btnToolNuevo.setFocusable(false);
        btnToolNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolNuevoActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolNuevo);

        btnToolModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Editar.png"))); // NOI18N
        btnToolModificar.setFocusable(false);
        btnToolModificar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolModificarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolModificar);

        btnToolGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Guardar.png"))); // NOI18N
        btnToolGuardar.setEnabled(false);
        btnToolGuardar.setFocusable(false);
        btnToolGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnToolGuardar);

        btnToolEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Eliminar.png"))); // NOI18N
        btnToolEliminar.setEnabled(false);
        btnToolEliminar.setFocusable(false);
        btnToolEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolEliminarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolEliminar);
        jToolBar1.add(jSeparator3);

        btnToolLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Limpiar.png"))); // NOI18N
        btnToolLimpiar.setFocusable(false);
        btnToolLimpiar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolLimpiar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolLimpiarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolLimpiar);

        btnToolBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Buscar.png"))); // NOI18N
        btnToolBuscar.setEnabled(false);
        btnToolBuscar.setFocusable(false);
        btnToolBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolBuscarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolBuscar);
        jToolBar1.add(jSeparator2);

        btnToolCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Cancelar.png"))); // NOI18N
        btnToolCancelar.setEnabled(false);
        btnToolCancelar.setFocusable(false);
        btnToolCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolCancelarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolCancelar);
        jToolBar1.add(jSeparator1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlBuscarProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(pnlResultadosProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(pnlBuscarProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlResultadosProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cambiarVista( JDesktopPane panel ){
        ((Index)(this.getTopLevelAncestor())).changeDesktopPane( panel );
    }
    
    private void btnToolNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToolNuevoActionPerformed
        cambiarVista( new Frm_RegistrarProducto() ) ; // <---------------------------- REGISTRAR
    }//GEN-LAST:event_btnToolNuevoActionPerformed

    private void btnToolModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToolModificarActionPerformed
        int i = this.tblBuscarProducto.getSelectedRow() ;
        if (i!=-1){
            int idProducto= Integer.parseInt(this.tblBuscarProducto.getValueAt(i, 0).toString());
                cambiarVista( new Frm_ModificarProducto(idProducto) ) ;        
        }    
        else{
            JOptionPane.showMessageDialog(this, "No se ha seleccionado ningún producto.");
        }       
        
    }//GEN-LAST:event_btnToolModificarActionPerformed

    private void btnToolLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToolLimpiarActionPerformed
        limpiar() ;
    }//GEN-LAST:event_btnToolLimpiarActionPerformed

    private void btnToolBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToolBuscarActionPerformed

    }//GEN-LAST:event_btnToolBuscarActionPerformed

    private void btnToolCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToolCancelarActionPerformed

    }//GEN-LAST:event_btnToolCancelarActionPerformed

    private void btnToolEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToolEliminarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnToolEliminarActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        try{
        String nombre = txtNombre.getText() ;
        List<Producto> lstProducto = ProductoPresenter.buscarProducto(nombre);
        
        mdlBuscarProducto.setNumRows( 0 ) ;
        mdlBuscarProducto = (DefaultTableModel)tblBuscarProducto.getModel() ;

        for(int i = 0 ; i < lstProducto.size() ; i++){
            Producto p = lstProducto.get( i ) ;
                String estado="";
                switch (p.getEstado()){
                    case 0: estado="Inactivo"; break;
                    case 1: estado="Activo"; break;
                }             
            Object[] row = new Object[]{ p.getIdProducto(), p.getNombre(),p.getPrecioCosto(),p.getPrecioLista(),p.getStock(),estado} ;
            mdlBuscarProducto.insertRow( i , row ) ;
        }
        tblBuscarProducto.setVisible( true ) ;

        JOptionPane.showMessageDialog(this, "Se encontraron "+ mdlBuscarProducto.getRowCount()+ " coincidencias");
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(this, "No se pudo realizar la transacción.");
            System.out.println("MENSAJE DE ERROR:"+e);
        }        
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        val.validaCaracteresRaros(evt);
        val.validaMaxSize(evt, 20, txtNombre.getText());
        txtNombre.setTransferHandler(null);
    }//GEN-LAST:event_txtNombreKeyTyped

    private void limpiar(){
        txtNombre.setText( "" ) ;
        mdlBuscarProducto.setNumRows( 0 ) ;
        mdlBuscarProducto = (DefaultTableModel)tblBuscarProducto.getModel() ;
    }    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btnBuscar;
    private javax.swing.JButton btnToolBuscar;
    private javax.swing.JButton btnToolCancelar;
    private javax.swing.JButton btnToolEliminar;
    private javax.swing.JButton btnToolGuardar;
    private javax.swing.JButton btnToolLimpiar;
    private javax.swing.JButton btnToolModificar;
    private javax.swing.JButton btnToolNuevo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JPanel pnlBuscarProducto;
    private javax.swing.JPanel pnlResultadosProducto;
    private javax.swing.JTable tblBuscarProducto;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
